import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import '../../controller/wallet_controller.dart';
import '../../model/wallet_model.dart';
import '../../routes/app_routes.dart';
import '../main/user_drawer.dart';

class WithdrawPage extends StatefulWidget {
  @override
  _WithdrawPageState createState() => _WithdrawPageState();
}

class _WithdrawPageState extends State<WithdrawPage> {
  late final WalletController walletController;
  final TextEditingController amountController = TextEditingController();
  final TextEditingController addressController = TextEditingController();

  // 选中的网络ID，默认为第一个可用网络
  int? selectedNetworkId;

  @override
  void initState() {
    super.initState();
    try {
      walletController = Get.find<WalletController>();
    } catch (e) {
      walletController = Get.put(WalletController());
    }
    _initializeData();
  }

  void _initializeData() {
    // 确保提现页面数据已加载
    walletController.loadWithdrawPageData();

    // 设置默认选中的网络
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final availableNetworks = walletController.availableNetworks;
      if (availableNetworks.isNotEmpty && selectedNetworkId == null) {
        setState(() {
          selectedNetworkId = availableNetworks.first.id;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFF1A1A1A),
      drawer: UserDrawer(),
      appBar: AppBar(
        backgroundColor: Color(0xFF1A1A1A),
        elevation: 0,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios_new, color: Colors.white),
          onPressed: () => Get.back(),
        ),
        title: Text('withdraw'.tr,
            style: TextStyle(
                color: Colors.white,
                fontSize: 18,
                fontWeight: FontWeight.w500)),
        centerTitle: true,
        actions: [
          IconButton(
            icon: Icon(Icons.history, color: Colors.orange),
            onPressed: () {
              Get.toNamed(AppRoutes.recordsDetail);
            },
          ),
          //   padding: EdgeInsets.only(right: 16),
          //   child: Center(
          //     child: Text(
          //       '历史',
          //       style: TextStyle(color: Colors.orange, fontSize: 16),
          //     ),
          //   ),
          // ),
        ],
      ),
      body: Obx(() {
        if (walletController.isLoadingWithdrawPageData.value) {
          return Center(
            child: CircularProgressIndicator(color: Colors.orange),
          );
        }

        return Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                padding: EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 说明文字
                    Container(
                      padding: EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: Color(0xFF2A2A2A),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Text(
                        'invalid_btc_address'.tr,
                        style:
                            TextStyle(color: Colors.orange[300], fontSize: 14),
                      ),
                    ),
                    SizedBox(height: 24),

                    // 金额部分
                    _buildAmountSection(),
                    SizedBox(height: 24),

                    // 网络选择
                    _buildNetworkSection(),
                    SizedBox(height: 24),

                    // 钱包地址
                    _buildAddressSection(),
                  ],
                ),
              ),
            ),

            // 底部信息和按钮
            _buildBottomSection(),
          ],
        );
      }),
    );
  }

  Widget _buildAmountSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'amount'.tr,
          style: TextStyle(
              color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500),
        ),
        SizedBox(height: 12),
        Container(
          padding: EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Color(0xFF2A2A2A),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: TextField(
                      controller: amountController,
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 18,
                          fontWeight: FontWeight.bold),
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText: 'input_withdrawal_amount'.tr,
                        hintStyle:
                            TextStyle(color: Colors.grey[400], fontSize: 18),
                      ),
                      keyboardType:
                          TextInputType.numberWithOptions(decimal: true),
                      inputFormatters: [
                        FilteringTextInputFormatter.allow(RegExp(r'^\d*\.?\d{0,8}')),
                        _DecimalTextInputFormatter(decimalRange: 8),
                      ],
                      onChanged: (value) {
                        setState(() {});
                      },
                    ),
                  ),
                  Text(
                    'BTC',
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 16,
                        fontWeight: FontWeight.w500),
                  ),
                ],
              ),
              SizedBox(height: 8),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '${'minimum_amount'.tr}：${_getMinWithdrawAmount()}',
                    style: TextStyle(color: Colors.grey[400], fontSize: 12),
                  ),
                  GestureDetector(
                    onTap: () {
                      // 使用WalletController的余额数据，格式化为8位小数
                      double balance = double.tryParse(walletController.availableBalance) ?? 0.0;
                      amountController.text = balance.toStringAsFixed(8);
                      setState(() {});
                    },
                    child: Text(
                      'withdraw_all'.tr,
                      style: TextStyle(
                          color: Colors.orange,
                          fontSize: 12,
                          fontWeight: FontWeight.w500),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildNetworkSection() {
    final availableNetworks = walletController.availableNetworks;

    if (availableNetworks.isEmpty) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'network'.tr,
            style: TextStyle(
                color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500),
          ),
          SizedBox(height: 12),
          Container(
            width: double.infinity,
            padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            decoration: BoxDecoration(
              color: Color(0xFF2A2A2A),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Text(
              'no_available_networks'.tr,
              style: TextStyle(color: Colors.grey[400], fontSize: 16),
            ),
          ),
        ],
      );
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'network'.tr,
          style: TextStyle(
              color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500),
        ),
        SizedBox(height: 12),
        Container(
          width: double.infinity,
          padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
          decoration: BoxDecoration(
            color: Color(0xFF2A2A2A),
            borderRadius: BorderRadius.circular(8),
          ),
          child: DropdownButtonHideUnderline(
            child: DropdownButton<int>(
              value: selectedNetworkId,
              icon: Icon(Icons.keyboard_arrow_down, color: Colors.white),
              dropdownColor: Color(0xFF2A2A2A),
              items: availableNetworks.map((NetworkConfigModel network) {
                return DropdownMenuItem<int>(
                  value: network.id,
                  child: Text(
                    network.title,
                    style: TextStyle(color: Colors.white, fontSize: 16),
                  ),
                );
              }).toList(),
              onChanged: (int? newValue) {
                setState(() {
                  selectedNetworkId = newValue;
                });
              },
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildAddressSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'wallet_address'.tr,
          style: TextStyle(
              color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500),
        ),
        SizedBox(height: 12),
        Container(
          padding: EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Color(0xFF2A2A2A),
            borderRadius: BorderRadius.circular(8),
          ),
          child: TextField(
            controller: addressController,
            style: TextStyle(color: Colors.white, fontSize: 16),
            decoration: InputDecoration(
              border: InputBorder.none,
              hintText: 'input_wallet_address'.tr,
              hintStyle: TextStyle(color: Colors.grey[400]),
            ),
            maxLines: 3,
            minLines: 1,
          ),
        ),
      ],
    );
  }



  Widget _buildBottomSection() {
    // 使用字符串计算保持精度
    String amountStr = amountController.text.trim();
    if (amountStr.isEmpty) amountStr = '0';

    // 获取网络费用（保持为字符串格式）
    String networkFeeStr = _getNetworkFeeString();

    // 使用高精度计算
    String receiveAmountStr = _calculateReceiveAmount(amountStr, networkFeeStr);

    return Container(
      padding: EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Color(0xFF1A1A1A),
        border: Border(top: BorderSide(color: Color(0xFF2A2A2A))),
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                'received_amount'.tr,
                style: TextStyle(color: Colors.white, fontSize: 14),
              ),
              Text(
                '$receiveAmountStr BTC',
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 14,
                    fontWeight: FontWeight.w500),
              ),
            ],
          ),
          SizedBox(height: 8),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                'network_fee'.tr,
                style: TextStyle(color: Colors.grey[400], fontSize: 14),
              ),
              Text(
                '$networkFeeStr BTC',
                style: TextStyle(color: Colors.grey[400], fontSize: 14),
              ),
            ],
          ),
          SizedBox(height: 16),
          Container(
            width: double.infinity,
            height: 48,
            child: ElevatedButton(
              onPressed: _handleWithdraw, // 移除条件判断，让方法内部处理
              style: ElevatedButton.styleFrom(
                padding: EdgeInsets.zero,
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(24)),
                elevation: 0,
              ),
              child: Ink(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(24),
                  gradient: _canSubmit()
                      ? LinearGradient(
                          colors: [Color(0xFFFFD700), Color(0xFFF0B90B)],
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                        )
                      : null,
                  color: _canSubmit() ? null : Color(0xFF4A4A4A),
                ),
                child: Container(
                  alignment: Alignment.center,
                  child: Text(
                    'withdraw'.tr,
                    style: TextStyle(
                      color: _canSubmit() ? Colors.black : Colors.grey[400],
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ),
            ),
          ),

          SizedBox(height: 30,)
        ],
        
      ),
    );
  }

  // 获取最小提现金额
  String _getMinWithdrawAmount() {
    if (selectedNetworkId == null) return '0.00060000';
    final config = walletController.getNetworkConfig(selectedNetworkId!);
    return config?.minimumAmount ?? '0.00060000';
  }

  // 获取网络费用字符串格式
  String _getNetworkFeeString() {
    if (selectedNetworkId == null) return '0.00015000';
    final config = walletController.getNetworkConfig(selectedNetworkId!);
    return config?.networkFee ?? '0.00015000';
  }

  // 获取网络费用（保持兼容性）
  double _getNetworkFee() {
    if (selectedNetworkId == null) return 0.00015;
    return walletController.getNetworkFee(selectedNetworkId!);
  }

  // 高精度计算收到金额
  String _calculateReceiveAmount(String amountStr, String networkFeeStr) {
    try {
      // 转换为整数计算（以聪为单位，1 BTC = 100,000,000 聪）
      double amount = double.parse(amountStr);
      double networkFee = double.parse(networkFeeStr);

      // 转换为聪进行计算
      int amountSatoshi = (amount * 100000000).round();
      int networkFeeSatoshi = (networkFee * 100000000).round();

      int receiveAmountSatoshi = amountSatoshi - networkFeeSatoshi;

      if (receiveAmountSatoshi <= 0) {
        return '0.00000000';
      }

      // 转换回BTC并格式化为8位小数
      double receiveAmount = receiveAmountSatoshi / 100000000.0;
      return receiveAmount.toStringAsFixed(8);
    } catch (e) {
      return '0.00000000';
    }
  }

  bool _canSubmit() {
    // 检查是否选择了网络
    if (selectedNetworkId == null) {
      return false;
    }
    
    double amount = double.tryParse(amountController.text) ?? 0.0;
    double minAmount = walletController.getMinWithdrawAmount(selectedNetworkId!);
    
    // 检查金额是否有效且地址是否已填写
    return amount >= minAmount && addressController.text.isNotEmpty;
  }

  void _handleWithdraw() async {
    // 检查各种条件并给出具体提示
    if (!_validateWithdrawConditions()) {
      return; // 如果验证失败，直接返回
    }

    print('提现按钮被点击');
    try {
      // 显示加载状态
      Get.dialog(
        Center(child: CircularProgressIndicator()),
        barrierDismissible: false,
      );

      // 调用提现API
      final response = await walletController.submitWithdrawRequest(
        amount: amountController.text,
        address: addressController.text,
        networkId: selectedNetworkId!,
      );

      Get.back(); // 关闭加载对话框

      if (response.success) {
        // 不再返回上一页，而是直接跳转到记录详情页并选中提现记录标签
        Get.offNamed(AppRoutes.recordsDetail, arguments: {'tabIndex': 1});
        // 然后显示成功提示
        Get.snackbar(
          'Tips',
          'Withdrawal successful.',
          backgroundColor: Colors.green,
          colorText: Colors.white,
        );
      } else {
        Get.snackbar(
          'Tips',
          'Withdrawal failed. Please try again later.',
          backgroundColor: Colors.red,
          colorText: Colors.white,
        );
      }
    } catch (e) {
      Get.back(); // 关闭加载对话框
      Get.snackbar(
        'Tips',
        'Withdrawal failed. Please try again later.',
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
    }
  }

// 新增验证方法，提供具体的错误提示
  bool _validateWithdrawConditions() {
    // 检查金额是否为空
    if (amountController.text.trim().isEmpty) {
      Get.snackbar(
        'Tips',
        'Please enter a withdrawal amount.',
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
      return false;
    }

    // 检查金额是否有效
    double amount = double.tryParse(amountController.text) ?? 0.0;
    if (amount <= 0) {
      Get.snackbar(
        'Tips',
        'Please enter a valid amount.',
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
      return false;
    }

    // 检查是否选择了网络
    if (selectedNetworkId == null) {
      Get.snackbar(
        'Tips',
        'Please select a network.',
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
      return false;
    }

    // 检查最小提现金额
    double minAmount =
        walletController.getMinWithdrawAmount(selectedNetworkId!);
    if (amount < minAmount) {
      Get.snackbar(
        'Tips',
        'Minimum withdrawal amount: ${minAmount.toStringAsFixed(8)} BTC',
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
      return false;
    }

    // 检查余额是否足够
    double availableBalance =
        double.tryParse(walletController.availableBalance) ?? 0.0;
    if (amount > availableBalance) {
      Get.snackbar(
        'Tips',
        'Insufficient balance. Available balance: ${availableBalance.toStringAsFixed(8)} BTC',
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
      return false;
    }

    // 检查钱包地址是否为空
    if (addressController.text.trim().isEmpty) {
      Get.snackbar(
        'Tips',
        'Please enter your wallet address.',
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
      return false;
    }

    // 简单的BTC地址格式验证
    // String address = addressController.text;
    // if (!_isValidBtcAddress(address)) {
    //   Get.snackbar(
    //     'error'.tr,
    //     'invalid_btc_address_format'.tr,
    //     backgroundColor: Colors.red,
    //     colorText: Colors.white,
    //   );
    //   return false;
    // }

    return true;
  }

// 简单的BTC地址格式验证
  bool _isValidBtcAddress(String address) {
    // BTC地址通常以1、3或bc1开头
    if (address.isEmpty) return false;

    // Legacy地址 (P2PKH) - 以1开头，25-34个字符
    if (address.startsWith('1') &&
        address.length >= 25 &&
        address.length <= 34) {
      return RegExp(r'^[13][a-km-zA-HJ-NP-Z1-9]{24,33}$').hasMatch(address);
    }

    // Script地址 (P2SH) - 以3开头，25-34个字符
    if (address.startsWith('3') &&
        address.length >= 25 &&
        address.length <= 34) {
      return RegExp(r'^[13][a-km-zA-HJ-NP-Z1-9]{24,33}$').hasMatch(address);
    }

    // Bech32地址 (P2WPKH/P2WSH) - 以bc1开头
    if (address.startsWith('bc1')) {
      return RegExp(r'^bc1[a-z0-9]{39,59}$').hasMatch(address);
    }

    return false;
  }

  @override
  void dispose() {
    amountController.dispose();
    addressController.dispose();
    super.dispose();
  }
}

// 自定义输入格式化器，限制小数位数
class _DecimalTextInputFormatter extends TextInputFormatter {
  final int decimalRange;

  _DecimalTextInputFormatter({required this.decimalRange});

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    String newText = newValue.text;
    
    // 如果输入为空，允许
    if (newText.isEmpty) {
      return newValue;
    }
    
    // 检查是否只包含数字和小数点
    if (!RegExp(r'^\d*\.?\d*$').hasMatch(newText)) {
      return oldValue;
    }
    
    // 检查小数点的数量
    if (newText.split('.').length > 2) {
      return oldValue;
    }
    
    // 检查小数位数
    if (newText.contains('.')) {
      List<String> parts = newText.split('.');
      if (parts[1].length > decimalRange) {
        return oldValue;
      }
    }
    
    // 防止以多个0开头（除了0.xxx的情况）
    if (newText.length > 1 && newText.startsWith('0') && !newText.startsWith('0.')) {
      return oldValue;
    }
    
    return newValue;
  }
}
